#!/usr/bin/env python3
# coding:utf-8

import paho.mqtt.client as mqtt


class MqttSubscriber:
    def __init__(self, broker_address, port=1883):
        self.broker_address = broker_address
        self.port = port
        # self.client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2)
        self.client = mqtt.Client()
        self.client.on_connect = self.on_connect
        self.client.on_message = self.on_message

    def on_connect(self, client, userdata, flags, rc):
        if rc == 0:
            print("Connected to MQTT Broker")
            # self.client.subscribe("font")
            topic_list=[("font",0),("back",0),("left",0),("right",0)]
            self.client.subscribe(topic_list)
        else:
            print(f"Failed to connect, return code {rc}")

    def on_message(self, client, userdata, msg):
        print(
            f"Received message '{msg.payload.decode()}' on topic '{msg.topic}'")

    def add_subscribe(self, topic_name):
        self.client.subscribe(topic_name)

    def del_subscribe(self, topic_name):
        self.client.unsubscribe(topic_name)

    def start(self):
        self.client.connect(self.broker_address, self.port)
        self.client.loop_start()

    def stop(self):
        self.client.disconnect()
        self.client.loop_stop()


# 使用示例
if __name__ == '__main__':
    subscriber = MqttSubscriber('127.0.0.1')
    subscriber.start()

    # 保持主程序运行，直到手动停止
    try:
        while True:
            pass
    except KeyboardInterrupt:
        subscriber.stop()
